package com.zangchat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.core.domain.AjaxResult;
import com.common.utils.StringUtils;
import com.zangchat.domain.ChatAccount;
import com.zangchat.domain.ChatLogCash;
import com.zangchat.domain.ChatUsers;
import com.zangchat.service.*;
import com.zangchat.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zangchat.mapper.ChatLogTalkMapper;
import com.zangchat.domain.ChatLogTalk;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 聊天记录 服务层实现
 *
 * @author ruoyi
 * @date 2020-07-29
 */
@Service
public class ChatLogTalkServiceImpl extends ServiceImpl<ChatLogTalkMapper, ChatLogTalk> implements IChatLogTalkService
{
    @Autowired
    private IChatUsersService chatUsersService;
    @Autowired
    private IChatSysConfigsService chatSysConfigsService;
    @Autowired
    private  IChatAccountService chatAccountService;
    @Autowired
    private IPageInfoService pageInfoService;
    @Autowired
    private IChatLogCashService chatLogCashService;

    @Transactional
    @Override
    public int saveLogTalk(Long fromId, Long receiveId, Date startTime, Date overTime, Long talkTime, int type,Boolean isFree) {
        ChatLogTalk chatLogTalk=new ChatLogTalk();
        chatLogTalk.setFromId(fromId);
        chatLogTalk.setReceiveId(receiveId);
        chatLogTalk.setStartTime(startTime);
        chatLogTalk.setTalkTime(talkTime);
        chatLogTalk.setType(type);
        chatLogTalk.setOverTime(overTime);
        String orderNo = StringUtils.getOrderIdByTime("v");
        BigDecimal amount=BigDecimal.ZERO;
        if (!isFree){
            if (type == 1) {
                BigDecimal talkCost = chatSysConfigsService.getValue("talk_cost", BigDecimal.class);
                amount = talkCost.multiply(new BigDecimal(talkTime));
            }
            if (type == 2) {
                BigDecimal videoCost = chatSysConfigsService.getValue("video_cost", BigDecimal.class);
                amount = videoCost.multiply(new BigDecimal(talkTime));
            }
            chatLogTalk.setAmount(amount);
            baseMapper.insert(chatLogTalk);
            ChatAccount chatAccount=new ChatAccount();
            chatAccount.setUserId(fromId);
            ChatAccount account = chatAccountService.getBaseMapper().selectOne(new QueryWrapper<ChatAccount>(chatAccount));
            BigDecimal ordinaryCash = account.getOrdinaryCash();

            //插入发起人流水
            ChatLogCash chatLogCashFrom = chatLogCashService.initQlwShopLogCash(2, fromId, 0L, orderNo, ordinaryCash, -1, amount, "视频");
            chatLogCashService.getBaseMapper().insert(chatLogCashFrom);
            //修改用户账户
            ChatAccount updateChatAccount=new ChatAccount();
            updateChatAccount.setOrdinaryCash(ordinaryCash.subtract(amount));
            chatAccountService.getBaseMapper().update(updateChatAccount,new UpdateWrapper<ChatAccount>(chatAccount));
        }
        //接收人获得
        //流水
        ChatAccount receiveAccount=new ChatAccount();
        receiveAccount.setUserId(receiveId);
        ChatAccount account = chatAccountService.getBaseMapper().selectOne(new QueryWrapper<ChatAccount>(receiveAccount));
        BigDecimal ordinaryCash = account.getOrdinaryCash();
        //插入接收人流水
        BigDecimal receiveAmount=BigDecimal.ZERO;
        if (type == 1) {
            BigDecimal talkCost = chatSysConfigsService.getValue("talk_cost", BigDecimal.class);
            BigDecimal talkProfit = chatSysConfigsService.getValue("talk_profit", BigDecimal.class);
            BigDecimal rate = talkProfit.divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
            receiveAmount = talkCost.multiply(new BigDecimal(talkTime)).multiply(rate);
        }
        if (type == 2) {
            BigDecimal videoCost = chatSysConfigsService.getValue("video_cost", BigDecimal.class);
            BigDecimal videoProfit = chatSysConfigsService.getValue("video_profit", BigDecimal.class);
            BigDecimal rate = videoProfit.divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
            receiveAmount = videoCost.multiply(new BigDecimal(talkTime)).multiply(rate);
        }
        ChatLogCash chatLogCashReceive = chatLogCashService.initQlwShopLogCash(2, 0L, receiveId, orderNo, ordinaryCash, 1, receiveAmount, "视频");
        chatLogCashService.getBaseMapper().insert(chatLogCashReceive);
        //修改用户账户
        ChatAccount updateChatAccount=new ChatAccount();
        updateChatAccount.setOrdinaryCash(ordinaryCash.add(receiveAmount));
        return chatAccountService.getBaseMapper().update(updateChatAccount,new UpdateWrapper<ChatAccount>(receiveAccount));

    }
    @Override
    public AjaxResult checkedTalk(Long fromId, Long receiveId, Date startTime, int type){
        AjaxResult ajaxResultFromUser = chatUsersService.checkedUser(fromId);
        if (Integer.parseInt(ajaxResultFromUser.get("code")+"")!=1){
            return ajaxResultFromUser;
        }
        AjaxResult ajaxResultReceiveUser = chatUsersService.checkedUser(receiveId);
        if (Integer.parseInt(ajaxResultReceiveUser.get("code")+"")!=1){
            return ajaxResultReceiveUser;
        }
        Map<String, Object> checkedFreeMap = this.checkedFree(fromId, startTime, type);
        int count = Integer.parseInt(checkedFreeMap.get("count") + "");
        int isCover = Integer.parseInt(checkedFreeMap.get("isCover") + "");
        if(isCover==1 && count>0){
            checkedFreeMap.put("isFree",true);
            return AjaxResult.success(checkedFreeMap);
        }else {
            Map<String, Object> map = this.getTimes(fromId, type);
            map.put("isCover",isCover);
            map.put("isFree",false);
            return   AjaxResult.success(map);
        }
    }

    @Override
    public AjaxResult selectLogTalk(Long userId, int pageNum, int pageSize) {
        AjaxResult ajaxResulUser = chatUsersService.checkedUser(userId);
        if (Integer.parseInt(ajaxResulUser.get("code")+"")!=1){
            return ajaxResulUser;
        }
        pageInfoService.initPagePageHelper(pageNum,pageSize);
        List<Map<String, Object>> list = baseMapper.selectLogTalkList(userId);
        Map<String, Object> resultMap = pageInfoService.initPageInfo(list);
        return AjaxResult.success(resultMap);
    }

    public Map<String,Object> checkedFree(Long userId,Date startTime,int type){
        Map<String,Object> resultMap=new HashMap<>();
        //查询是否有免费次数
        ChatUsers chatUsers = chatUsersService.getBaseMapper().selectById(userId);
        Integer isCover = chatUsers.getIsCover();//暂定此字段为会员标识
        resultMap.put("isCover",isCover);
        resultMap.put("count",0);
        resultMap.put("times",0);
        resultMap.put("type",type);
        if (isCover==1){
            Map<String,Object> map=new HashMap<>();
            map.put("userId",userId);
            String date ="";
            try {
                date= DateUtil.dateToStr(startTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            map.put("startTime",startTime);
            map.put("date",date);
            map.put("type",type);
            Integer count = baseMapper.selectLogTalkCount(map);//今日已聊次数
            if (type==1){ //聊天
                Integer freeTalkCount = chatSysConfigsService.getValue("free_talk_count", Integer.class);
                if (freeTalkCount>=count) {
                    Long freeTalktimes = chatSysConfigsService.getValue("free_talk_times", Long.class);
                    resultMap.put("count", freeTalkCount - count);
                    resultMap.put("times", freeTalktimes);
                    resultMap.put("type", type);
                }
            }
            if (type==2){ //视频
                Integer freeVdeoCount = chatSysConfigsService.getValue("free_video_count", Integer.class);
                if (freeVdeoCount>=count){
                    Long freeVideoTimes = chatSysConfigsService.getValue("free_video_times", Long.class);
                    resultMap.put("count",freeVdeoCount-count);
                    resultMap.put("times",freeVideoTimes);
                    resultMap.put("type",type);
                }
            }
        }
        return resultMap;
    }

    public Map<String,Object> getTimes(Long userId,int type){
        Map<String,Object> resultMap=new HashMap<>();
        ChatAccount chatAccount=new ChatAccount();
        chatAccount.setUserId(userId);
        ChatAccount account = chatAccountService.getBaseMapper().selectOne(new QueryWrapper<ChatAccount>(chatAccount));
        BigDecimal ordinaryCash = account.getOrdinaryCash();
        BigDecimal times=BigDecimal.ZERO;
        if (BigDecimal.ZERO.compareTo(ordinaryCash)==1){
            resultMap.put("count",0);
            resultMap.put("times",times);
            resultMap.put("type",type);
            return resultMap;
        }
        if (type==1){
            BigDecimal talkCost = chatSysConfigsService.getValue("talk_cost", BigDecimal.class);
            times = ordinaryCash.divideToIntegralValue(talkCost);
        }
        if (type==2){
            BigDecimal videoCost = chatSysConfigsService.getValue("video_cost", BigDecimal.class);
            times = ordinaryCash.divideToIntegralValue(videoCost);
        }
        resultMap.put("count",1);
        resultMap.put("times",times);
        resultMap.put("type",type);
        return resultMap;
    }
}